//
//  WSJPopview.m
//  BaxTer
//
//  Created by wsj2015 on 16/9/1.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "WSJPopview.h"
#import "KLCPopup.h"

#import "LDProgressView.h"
#import "BTRatingView.h"

#import "CKHttpCommunicate.h"
#import "HELPDFfileCacheTool.h"
@interface WSJPopview ()

@property (nonatomic,  strong) KLCPopup *pop;

@property (nonatomic,  strong) LDProgressView *progressView;


@property (nonatomic,  strong) UILabel *titleL;

@property (nonatomic,  strong) NSString *urlStr;

@property (nonatomic,  strong) NSString *pdfName;
@property (nonatomic, strong) NSURLSessionDownloadTask *downTask;

@property (nonatomic,  strong) UIButton *canBtn;

@end
@implementation WSJPopview

+ (instancetype)sharedWsjPopView{
  
     return [[WSJPopview alloc] init];
   
    
 
}
- (void)showRatingView:(BOOL)isAbleRate withHelpScore:(CGFloat)helpScore withContentScore:(CGFloat)contentScore withDoneBlock:(void(^)(CGFloat help_score,CGFloat content_score))doneBlock{
    
       CGFloat f = kScreenFactor;
    weakSelf_define;
    BTRatingView *ratingView = [BTRatingView ratingView];
   
    ratingView.frame =CGRectMake(0, 0, 300 * f, 180);
    __weak KLCPopup *pop =  [KLCPopup popupWithContentView:ratingView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOutToTop maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];

    [pop show];
    __weak typeof(ratingView) weakR = ratingView;
    if (isAbleRate == YES) {
        ratingView.confirmBlock = ^(CGFloat h,CGFloat c){
          
            doneBlock(h,c);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakR removeFromSuperview];
            });
            [pop dismiss:YES];
        };
       
        
    }else{
     
        ratingView.help_score = helpScore;
        ratingView.contet_score = contentScore;
        ratingView.ableToRate = NO;
        
        ratingView.confirmBlock = ^(CGFloat h,CGFloat c){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakR removeFromSuperview];
            });
            [pop dismiss:YES];
        };
        
    }

}



- (void)startDownload{
    
    weakSelf_define;
    __block BOOL isFail = 0;
   self.downTask = [CKHttpCommunicate createDownloadFileWithURLString:self.urlStr downloadFileProgress:^(NSProgress *progress) {
       if (isFail == 1) {
           return ;
       }
//       __block typeof(weakSelf) self = weakSelf;
        dispatch_sync(dispatch_get_main_queue(), ^{
                    
            self.progress = progress.fractionCompleted;
            if (progress.fractionCompleted >= 1) {
                weakSelf.titleL.text  =@"下载完成";
                if (weakSelf.doneBlock) {
                    weakSelf.doneBlock();
                }
                [weakSelf.canBtn setTitle:@"确定" forState:UIControlStateNormal];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [self.pop dismiss:YES];
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    [self clear];
                                });
                            });
                
            }

//            hud.label.text = [NSString stringWithFormat:@"已下载%.f%%",progress.fractionCompleted *100];
        });
        
        //        NSLog(@"---%f,%f",progress,progress.completedUnitCount);
        
    } setupFilePath:^NSURL *(NSURLResponse *response) {
        
        //        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [NSURL fileURLWithPath: [HELPDFfileCacheTool getDownloadPathWithPdfName:weakSelf.pdfName]];
        
    } downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
      
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (error) {
                isFail = 1;
                alertMessage(error.localizedDescription);
//                [weakSelf btnClick];
                [self.pop dismiss:YES];
                
            }
        });
//        NSString *fullPath = [filePath path];
       
        
        
    }];

}

- (instancetype)showDownLoadWithUrl:(NSString *)url withPdfName:(NSString *)pdfName{
    
    self.urlStr = url;
    self.pdfName = pdfName;
    UIView *view =[UIView new];
      CGFloat f = kScreenFactor;
    view.frame = CGRectMake(0, 0, 268 * f, f *130);
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    
    CGFloat w = 268 * f;
    UILabel *label = [UILabel new];
    label.frame = CGRectMake(0, 15, w, 20);
    label.font = [UIFont systemFontOfSize:17];
    label.text = @"正在下载中...";
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    
    self.titleL = label;
    
    LDProgressView * progressView = [[LDProgressView alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(label.frame) + 10 *f, w-40, 22)];
    progressView.color = [UIColor greenColor];
    progressView.flat = @YES;
    progressView.progress = 0.0;
    progressView.animate = @YES;
    progressView.showText = @YES;
//    progressView.showStroke = @YES;
    progressView.progressInset = @0;
    progressView.showBackground = @YES;
//    progressView.backgroundColor = [UIColor lightGrayColor];
//    progressView.outerStrokeWidth = @1;
    progressView.type = LDProgressGradient;
//    progressView.showTextAlways = @YES;
//    progressView.textColor = [UIColor whiteColor];
//    progressView.textAlignment =@(0);
    [view addSubview:progressView];
    self.progressView = progressView;
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
//    btn.center = CGPointMake(view.center.x, );
    CGFloat btnw = 120 *f;
    btn.frame = CGRectMake((w - btnw) /2, CGRectGetMaxY(progressView.frame) + 10 * f, 120 *f, 33);
    [btn setBackgroundColor:kMainColor];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    [view addSubview:btn];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius = 10;
    btn.layer.masksToBounds = YES;
    self.canBtn = btn;
    self.pop =  [KLCPopup popupWithContentView:view showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOut maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    [self.pop show];
    [self.pop setValue:@(1) forKey:@"isShowing"];
    weakSelf_define;
    self.pop.didFinishDismissingCompletion = ^(){
    
        [weakSelf clear];
    };
    
    

    
    [self startDownload];
    
    
    
    return self;

}




- (void)btnClick{
   
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
    self.titleL.text  =@"取消中...";
    self.progress = 0.0;
    [self.downTask cancel];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.pop dismiss:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self clear];
        });
    });

   
    
}
- (void)clear{

    self.downTask = nil;
//    [self.progressView removeObserver:self forKeyPath:@"progress"];
    
    for (UIView *v in self.pop.subviews) {
        [v removeFromSuperview];
    }
  
    self.pop = nil;

   
}


- (void)dealloc{
    
    
}
- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    self.progressView.progress = progress;
}
@end
